﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AioNightly.Model;
using MySql.Data.MySqlClient;
using AioNightly.Common;

namespace AioNightly.Dao
{
    public class BuildDAO
    {
        private void Read2List(MySqlDataReader reader, List<Build> list)
        {
            while (reader.Read())
            {
                Build it = new Build();
                it.Id = reader.GetInt32(0);
                it.PVersionId = reader.GetInt32(1);
                it.CreateTime = reader.GetString(2);

                list.Add(it);
            }
        }

        public List<Build> GetBuildByVersion(string versionName)
        {
            DBConnect db = new DBConnect();
            db.OpenConnection();

            List<Build> list = new List<Build>();
            string sql = string.Format("SELECT b.Id, b.PVersionId, b.BuildTime, v.Id AS Expr1, v.ProductId, v.VersionName FROM build b INNER JOIN pversion v ON b.PVersionId = v.Id WHERE (v.VersionName = '{0}')", versionName);
            MySqlCommand cmd = new MySqlCommand(sql, db.Conn);
            MySqlDataReader reader = cmd.ExecuteReader();

            Read2List(reader, list);

            if(reader!=null)
                reader.Close();

            db.CloseConnection();

            return list;
        }

        public int GetIdByCreateTime(string time)
        {
            DBConnect db = new DBConnect();
            db.OpenConnection();

            List<Build> list = new List<Build>();
            string sql = string.Format("select * from build where buildtime='{0}'", time);
            MySqlCommand cmd = new MySqlCommand(sql, db.Conn);
            MySqlDataReader reader = cmd.ExecuteReader();

            Read2List(reader, list);

            if (reader != null)
                reader.Close();

            db.CloseConnection();

            if (list.Count==1)
            {
                return list[0].Id;
            } 
            else
            {
                return -1;
            }
        }

        public int AddBuildNow(int pversionid)
        {
            DBConnect db = new DBConnect();
            db.OpenConnection();

            string sql = string.Format("insert into build (pversionid,buildtime) values ({0},'{1}')", pversionid, TimeManager.GetSystemTime());
            MySqlCommand cmd = new MySqlCommand(sql, db.Conn);
            int result = cmd.ExecuteNonQuery();

            return result;
        }
    }
}